<template>
    <div class="user-list-container">
        <!-- 页面标题 -->
        <div class="header-title">会议室管理</div>

        <!-- 查询与筛选区域 -->
        <el-form :inline="true" class="filter-form" size="small">
            <el-input v-model="search.RoomName" placeholder="请输入会议室名称" style="width: 200px; margin-right: 8px" />
            <el-button type="primary" @click="GetRoomList">查询</el-button>
            <el-button @click="ResetInfo">重置</el-button>
        </el-form>

        <!-- 操作按钮 -->
        <div class="action-btns" style="margin-bottom: 16px;">
            <el-button type="primary" @click="openNewRoomDialog">新增</el-button>
            <el-button @click="BatchDelete">批量删除</el-button>
        </div>

        <!-- 会议室数据表格 -->
        <el-table :data="RoomInfo" border stripe size="small" style="width: 100%" @selection-change="onSelectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column prop="roomName" label="会议室名称" width="250">
                <template #default="scope">
                    <div style="display: flex; align-items: center;">
                        <img v-if="scope.row.roomImage" :src="`http://localhost:5195${scope.row.roomImage}`" alt="会议室图片"
                            style="width: 40px; height: 40px; margin-right: 10px; object-fit: cover;" />
                        <span>{{ scope.row.roomName }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="capacity" label="容纳人数" width="100" />
            <el-table-column prop="location" label="会议室位置" />
            <el-table-column prop="administrator" label="管理员" />
            <el-table-column prop="contactNumber" label="联系电话" />
            <el-table-column prop="reservationApproval" label="预约审批" width="120">
                <template #default="scope">
                    <span v-if="scope.row.reservationApproval">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column prop="isSmartRoom" label="智能会议室" width="120">
                <template #default="scope">
                    <span v-if="scope.row.isSmartRoom">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-button type="text" style="color: #409eff;" @click="openViewRoomDialog(scope.row)">查看</el-button>
                    <el-button type="text" style="color: #67c23a;" @click="openEditRoomDialog(scope.row)">修改</el-button>
                    <el-button type="text" style="color: #f56c6c;" @click="DeleteMeetRoom(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style=" margin-top: 10px;">
            <el-pagination v-model:current-page="Pageinfo.pageIndex" v-model:page-size="Pageinfo.pageSize"
                :page-sizes="[5, 10, 20]" :size="Pageinfo.pageSize" :disabled="false" :background="true"
                layout="total,slot" :total="Pageinfo.totalCount" prev-text="上一页" next-text="下一页">
                第{{ Pageinfo.pageIndex }}/{{ Pageinfo.pageCount }}页
            </el-pagination>

            <el-pagination v-model:current-page="Pageinfo.pageIndex" v-model:page-size="Pageinfo.pageSize"
                :page-sizes="[5, 10, 20]" :size="Pageinfo.pageSize" :disabled="false" :background="true"
                layout=" sizes,slot, prev, pager, next" :total="Pageinfo.totalCount" prev-text="上一页" next-text="下一页">
                <el-button :disabled="Pageinfo.pageIndex == 1" @click="Pageinfo.pageIndex = 1">首页</el-button>
            </el-pagination>

            <el-pagination v-model:current-page="Pageinfo.pageIndex" v-model:page-size="Pageinfo.pageSize"
                :page-sizes="[5, 10, 20]" :size="Pageinfo.pageSize" :disabled="false" :background="true"
                layout="slot, jumper" :total="Pageinfo.totalCount" prev-text="上一页" next-text="下一页">
                <el-button :disabled="Pageinfo.pageIndex == Pageinfo.pageCount"
                    @click="Pageinfo.pageIndex = Pageinfo.pageCount">尾页</el-button>
            </el-pagination>
        </el-row>

        <!-- 新增会议室对话框 -->
        <el-dialog title="新增会议室" v-model="newRoomDialogVisible" width="40%" @close="resetNewRoomForm">
            <el-form :model="newRoomForm" :rules="newRoomRules" ref="newRoomFormRef" label-width="120px">
                <div style="display: flex;">
                    <div style="flex: 1; margin-right: 20px;">
                        <div class="form-section-title">基本信息</div>
                        <el-form-item label="会议室名称" prop="roomName" required>
                            <el-input v-model="newRoomForm.roomName" placeholder="请选择会议室模板"
                                style="width: 250px;"></el-input>
                        </el-form-item>
                        <el-form-item label="容纳人数" prop="capacity" required>
                            <el-input-number v-model.number="newRoomForm.capacity" :min="0" placeholder="请输入容纳人数"
                                style="width: 250px;" />
                        </el-form-item>
                        <el-form-item label="会议室位置" prop="location" required>
                            <el-select v-model="newRoomForm.location" placeholder="请选择会议室位置" style="width: 250px;">
                                <el-option v-for="item in roomLocations" :key="item" :label="item" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="会议室管理员" prop="administrator" required>
                            <el-input v-model="newRoomForm.administrator" placeholder="参与人"
                                style="width: 250px;"></el-input>
                        </el-form-item>
                        <el-form-item label="联系电话" prop="contactNumber" required>
                            <el-input v-model="newRoomForm.contactNumber" placeholder="会议内容" style="width: 250px;"
                                MaxLength="11"></el-input>
                        </el-form-item>
                    </div>
                    <div style="width: 150px;">
                        <!-- 图片上传 -->
                        <el-upload class="avatar-uploader" action="http://localhost:5195/api/Upload/UploadImage"
                            :show-file-list="false" name="formFile" :on-success="handleAvatarSuccess">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>
                </div>

                <el-form-item label="">
                    <el-checkbox v-model="newRoomForm.reservationApproval" label="预约审批"></el-checkbox>
                    <el-checkbox v-model="newRoomForm.isSmartRoom" label="智能会议室"
                        style="margin-left: 30px;"></el-checkbox>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="newRoomDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveNewRoom">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 会议室详情对话框 -->
        <el-dialog title="会议室详情" v-model="viewRoomDialogVisible" width="40%">
            <el-form :model="viewedRoomDetails" label-width="120px" v-if="viewedRoomDetails">
                <div style="display: flex;">
                    <div style="flex: 1; margin-right: 20px;">
                        <div class="form-section-title">基本信息</div>
                        <el-form-item label="会议室名称">
                            <span>{{ viewedRoomDetails.roomName }}</span>
                        </el-form-item>
                        <el-form-item label="容纳人数">
                            <span>{{ viewedRoomDetails.capacity }}</span>
                        </el-form-item>
                        <el-form-item label="会议室位置">
                            <span>{{ viewedRoomDetails.location }}</span>
                        </el-form-item>
                        <el-form-item label="会议室管理员">
                            <span>{{ viewedRoomDetails.administrator }}</span>
                        </el-form-item>
                        <el-form-item label="联系电话">
                            <span>{{ viewedRoomDetails.contactNumber }}</span>
                        </el-form-item>
                    </div>
                    <div style="width: 150px;">
                        <!-- 图片展示 -->
                        <img v-if="viewedRoomDetails.roomImage"
                            :src="`http://localhost:5195${viewedRoomDetails.roomImage}`" alt="会议室图片"
                            style="width: 120px; height: 120px; object-fit: cover; border-radius: 6px;" />
                        <div v-else
                            style="width: 120px; height: 120px; border: 1px dashed #d9d9d9; border-radius: 6px; display: flex; justify-content: center; align-items: center; color: #8c939d;">
                            暂无图片</div>
                    </div>
                </div>

                <el-form-item label="">
                    <el-checkbox v-model="viewedRoomDetails.reservationApproval" label="预约审批" disabled></el-checkbox>
                    <el-checkbox v-model="viewedRoomDetails.isSmartRoom" label="智能会议室" style="margin-left: 30px;"
                        disabled></el-checkbox>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改会议室对话框 -->
        <el-dialog title="修改会议室" v-model="editRoomDialogVisible" width="40%" @close="resetEditRoomForm">
            <el-form :model="editRoomForm" :rules="newRoomRules" ref="editRoomFormRef" label-width="120px">
                <div style="display: flex;">
                    <div style="flex: 1; margin-right: 20px;">
                        <div class="form-section-title">基本信息</div>
                        <el-form-item label="会议室名称" prop="roomName" required>
                            <el-input v-model="editRoomForm.roomName" placeholder="请输入会议室名称"
                                style="width: 250px;"></el-input>
                        </el-form-item>
                        <el-form-item label="容纳人数" prop="capacity" required>
                            <el-input-number v-model.number="editRoomForm.capacity" :min="0" placeholder="请输入容纳人数"
                                style="width: 250px;" />
                        </el-form-item>
                        <el-form-item label="会议室位置" prop="location" required>
                            <el-select v-model="editRoomForm.location" placeholder="请选择会议室位置" style="width: 250px;">
                                <el-option v-for="item in roomLocations" :key="item" :label="item" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="会议室管理员" prop="administrator" required>
                            <el-input v-model="editRoomForm.administrator" placeholder="请输入管理员"
                                style="width: 250px;"></el-input>
                        </el-form-item>
                        <el-form-item label="联系电话" prop="contactNumber" required>
                            <el-input v-model="editRoomForm.contactNumber" placeholder="请输入联系电话" style="width: 250px;"
                                MaxLength="11"></el-input>
                        </el-form-item>
                    </div>
                    <div style="width: 150px;">
                        <!-- 图片上传 -->
                        <el-upload class="avatar-uploader" action="http://localhost:5195/api/Upload/UploadImage"
                            :show-file-list="false" name="formFile" :on-success="handleEditAvatarSuccess">
                            <img v-if="editImageUrl" :src="editImageUrl" class="avatar">
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>
                </div>

                <el-form-item label="">
                    <el-checkbox v-model="editRoomForm.reservationApproval" label="预约审批"></el-checkbox>
                    <el-checkbox v-model="editRoomForm.isSmartRoom" label="智能会议室"
                        style="margin-left: 30px;"></el-checkbox>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editRoomDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveEditedRoom">确定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import moment from "moment";
import { ElMessageBox, ElMessage, ElInputNumber, ElUpload } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { AddRoom, GetRoom, DeleteRoom, UpdateRoom, BatchDeleteRoom } from "@/Api/room";
import { Plus } from '@element-plus/icons-vue'

const Delarr = ref([])

const onSelectionChange = (selection: any) => {
    // 多选逻辑
    Delarr.value = selection.map((item: any) => (item.id))
    console.log(Delarr);
}

//批量删除部门
const BatchDelete = async () => {
    ElMessageBox.confirm(
        '确定要删除会议室吗？此操作不可撤销！',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 调用后端接口删除
        const response = await BatchDeleteRoom(Delarr.value)
        console.log(response);
        
        if (response.data.code == 200) {
            ElMessage.success('删除成功！')
            GetRoomList()
        }
        if (response.data.code == 500) {
            ElMessage.error(response.data.message)
        }


    }).catch(() => {
        // 用户取消，无需处理
    })
}



//查询条件信息
const search = reactive({
    RoomName: "",
});

//重置查询条件
const ResetInfo = () => {
    search.RoomName = ""
    GetRoomList();
}

//分页条件信息
const Pageinfo = reactive({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    pageCount: 0,
});

//会议室列表
const RoomInfo = ref([])

//获取会议室列表
const GetRoomList = async () => {
    var params = {
        pageIndex: Pageinfo.pageIndex,
        pageSize: Pageinfo.pageSize,
        RoomName: search.RoomName,
    }
    var response = await GetRoom(params);
    RoomInfo.value = response.data.data.pageData
    Pageinfo.totalCount = response.data.data.totalCount
    Pageinfo.pageCount = response.data.data.pageCount
}



// 控制新增会议室对话框的显示隐藏
const newRoomDialogVisible = ref(false);

// 新增会议室表单ref
const newRoomFormRef = ref<FormInstance>()

// 新增会议室表单
const newRoomForm = reactive({
    roomName: '',
    capacity: 0,
    location: '',
    administrator: '',
    contactNumber: '',
    reservationApproval: false,
    isSmartRoom: false,
    roomImage: '', // 用于存储图片路径
});

// 控制会议室详情对话框的显示隐藏
const viewRoomDialogVisible = ref(false);

// 当前查看的会议室详情数据
const viewedRoomDetails = ref<any>(null);

// 控制修改会议室对话框的显示隐藏
const editRoomDialogVisible = ref(false);

// 当前编辑的会议室表单
const editRoomForm = reactive<any>({
    id: null,
    roomName: '',
    capacity: 0,
    location: '',
    administrator: '',
    contactNumber: '',
    reservationApproval: false,
    isSmartRoom: false,
    roomImage: '',
});

// 修改会议室表单ref
const editRoomFormRef = ref<FormInstance>()

// 用于修改对话框的图片预览URL
const editImageUrl = ref('');

// 新增会议室表单校验规则
const newRoomRules = reactive<FormRules>({
    roomName: [
        { required: true, message: '请输入会议室名称', trigger: 'blur' }
    ],
    capacity: [
        { required: true, message: '请输入容纳人数', trigger: 'change' }
    ],
    location: [
        { required: true, message: '请选择会议室位置', trigger: 'change' }
    ],
    administrator: [
        { required: true, message: '请输入会议室管理员', trigger: 'blur' }
    ],
    contactNumber: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
    ],
})

// 打开新增会议室对话框
const openNewRoomDialog = () => {
    newRoomDialogVisible.value = true;
    // 可以在这里加载会议室位置等数据
};

// 关闭新增会议室对话框时重置表单和校验状态
const resetNewRoomForm = () => {
    if (newRoomFormRef.value) {
        newRoomFormRef.value.resetFields(); // 重置表单校验状态
    }
    // 手动重置其他字段
    newRoomForm.roomName = '';
    newRoomForm.capacity = 0;
    newRoomForm.location = '';
    newRoomForm.administrator = '';
    newRoomForm.contactNumber = '';
    newRoomForm.reservationApproval = false;
    newRoomForm.isSmartRoom = false;
    newRoomForm.roomImage = '';
    imageUrl.value = ''; // 重置图片预览
};

// 保存新增会议室
const saveNewRoom = async () => {
    if (!newRoomFormRef.value) return;

    newRoomFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log("保存新增的会议室信息:", newRoomForm);
            // 调用后端接口保存新增会议室
            const response = await AddRoom(newRoomForm);
            if (response.data && response.data.code === 200) {
                ElMessage.success("新增会议室成功!");
                newRoomDialogVisible.value = false;
                GetRoomList(); // 刷新列表
            } else {
                ElMessage.error("新增会议室失败，请重试!"); // 或者显示后端返回的错误信息
            }
        } else {
            console.log('表单校验失败');
        }
        return; // 显式返回 void
    });
};

// 图片上传相关
const imageUrl = ref('');

// 会议室位置示例数据
const roomLocations = ref(['会议室A', '会议室B', '会议室C', '会议室D', '会议室E']);

//上传成功后获取图片路径
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response, uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
    newRoomForm.roomImage = response.data
    if (response.data == null) {
        ElMessage.error('获取图片URL失败！');
    }
    console.log(newRoomForm.roomImage);

}

//删除部门
const DeleteMeetRoom = async (id: any) => {
    ElMessageBox.confirm(
        '确定要删除该会议室吗？此操作不可撤销！',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 调用后端接口删除
        await DeleteRoom(id)
        ElMessage.success('删除成功！')
        GetRoomList()
    }).catch(() => {
        // 用户取消，无需处理
    })
}

// 打开会议室详情对话框
const openViewRoomDialog = (room: any) => {
    viewedRoomDetails.value = room;
    viewRoomDialogVisible.value = true;
};

// 打开修改会议室对话框
const openEditRoomDialog = (room: any) => {
    // 复制当前会议室数据到编辑表单
    Object.assign(editRoomForm, room);
    // 如果有图片，设置图片预览
    if (room.roomImage) {
        editImageUrl.value = `http://localhost:5195${room.roomImage}`;
    } else {
        editImageUrl.value = '';
    }
    editRoomDialogVisible.value = true;
};

// 关闭修改会议室对话框时重置表单和校验状态
const resetEditRoomForm = () => {
    if (editRoomFormRef.value) {
        editRoomFormRef.value.resetFields(); // 重置表单校验状态
    }
    // 手动重置其他字段
    editRoomForm.id = null;
    editRoomForm.roomName = '';
    editRoomForm.capacity = 0;
    editRoomForm.location = '';
    editRoomForm.administrator = '';
    editRoomForm.contactNumber = '';
    editRoomForm.reservationApproval = false;
    editRoomForm.isSmartRoom = false;
    editRoomForm.roomImage = '';
    editImageUrl.value = ''; // 重置图片预览
};

// 保存修改后的会议室 (需要调用后端更新接口)
const saveEditedRoom = async () => {
    if (!editRoomFormRef.value) return;

    editRoomFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log("保存修改的会议室信息:", editRoomForm);
            // 调用后端更新会议室接口并处理响应
            const response = await UpdateRoom(editRoomForm);
            if (response.data && response.data.code === 200) {
                ElMessage.success("修改会议室成功!");
                editRoomDialogVisible.value = false;
                GetRoomList(); // 刷新列表
            } else {
                ElMessage.error("修改会议室失败，请重试!"); // 或者显示后端返回的错误信息
            }
            ElMessage.info("模拟保存成功，请连接后端更新接口。"); // 临时提示
            editRoomDialogVisible.value = false;
        } else {
            console.log('表单校验失败');
        }
        return;
    });
};

//上传成功后获取图片路径 (用于修改对话框)
const handleEditAvatarSuccess: UploadProps['onSuccess'] = (
    response, uploadFile
) => {
    editImageUrl.value = URL.createObjectURL(uploadFile.raw!);
    editRoomForm.roomImage = response.data
    if (response.data == null) {
        ElMessage.error('获取图片URL失败！');
    }
    console.log(editRoomForm.roomImage);
}

//监听分页条件信息
watch(Pageinfo, () => {
    GetRoomList();
}, { deep: true })

//文档就绪
onMounted(() => {
    GetRoomList();
});

</script>

<style scoped>
.user-list-container {
    background: #fff;
    padding: 2% 3%;
    border-radius: 0.5em;
}

.header-title {
    font-size: 1.3em;
    font-weight: bold;
    margin-bottom: 2%;
}

.filter-form {
    margin-bottom: 1.5%;
}

.action-btns {
    margin-bottom: 1.5%;
}

.main-container {
    max-width: 100%;
    margin: 0 auto;
    width: 100%;
    /* 可根据需要加padding: 2% 3%; */
}

.detail-form .el-form-item__label {
    color: #666;
    font-weight: bold;
}

.el-table .el-table__cell {
    padding: 6px 8px !important;
    font-size: 14px;
}

.form-section-title {
    font-size: 1em;
    font-weight: bold;
    margin-bottom: 15px;
    padding-left: 10px;
    border-left: 4px solid #409eff;
    /* 蓝色条 */
}

/* 图片上传样式 */
.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}

.el-form-item {
    margin-bottom: 18px;
    /* 增加表单项之间的垂直间距 */
}
</style>
